import xlrd
import os
import re

def get_excel_files():
    directory = os.path.dirname(os.path.abspath(__file__))
    excel_files = []
    for file in os.listdir(directory):
        if file.endswith('.xls') and '课表' in file:
            excel_files.append(os.path.join(directory, file))
    return excel_files

def extract_course_name(text):
    """从文本中提取课程名称"""
    if not text:
        return None
    
    # 常见的课程格式：课程名/(时间)/地点/教师/人数
    pattern = r'^([^/]+)'  # 提取第一个斜杠前的内容作为课程名
    match = re.match(pattern, text)
    if match:
        course_name = match.group(1).strip()
        # 过滤掉非课程名称
        if len(course_name) > 2 and not any(keyword in course_name for keyword in ['星期一', '星期二', '星期三', '星期四', '星期五']):
            return course_name
    return None

def analyze_course_files():
    excel_files = get_excel_files()
    course_set = set()
    
    print(f"找到 {len(excel_files)} 个课表文件")
    
    for file_path in excel_files:
        print(f"\n正在分析文件: {os.path.basename(file_path)}")
        try:
            workbook = xlrd.open_workbook(file_path)
            worksheet = workbook.sheet_by_index(0)
            
            # 遍历所有单元格寻找课程信息
            for row in range(worksheet.nrows):
                for col in range(worksheet.ncols):
                    cell_value = str(worksheet.cell_value(row, col))
                    if cell_value and len(cell_value) > 2:
                        # 尝试提取课程名
                        course_name = extract_course_name(cell_value)
                        if course_name:
                            course_set.add(course_name)
        
        except Exception as e:
            print(f"处理文件 {os.path.basename(file_path)} 时出错: {str(e)}")
    
    # 显示提取到的所有课程
    print(f"\n总共提取到 {len(course_set)} 门课程:")
    for i, course in enumerate(sorted(course_set), 1):
        print(f"{i}. {course}")

if __name__ == "__main__":
    analyze_course_files()